angular
    .module('app.service')
    .service('UserService', UserService);

UserService.$inject = ['HOST','API', '$http','$window'];
function UserService(HOST,API, $http,$window) {
    var baseUrl = API + 'admin/users';
    var authData;
    this.auth = auth;
    this.logout = logout;
    this.getUser = getUser;
    this.changePassword = changePassword;
    this.isAuthenticated = isAuthenticated;
    this.remove = remove;
    this.save = save;
    this.list = list;

    function _storeUser(user){
        $window.sessionStorage.userId = user.id;
        $window.sessionStorage.name = user.name;
        $window.sessionStorage.workId = user.workId;
        $window.sessionStorage.role = user.role;
        $window.sessionStorage.subject = user.subject;
        $window.sessionStorage.markRight = user.markRight;
    }

    ////////////////
    function auth(user){
        _storeUser(user);
    }

    function logout(callback){
        $http.delete(HOST+'logout')
        .success(function(){
            delete $window.sessionStorage.userId;
            delete $window.sessionStorage.name;
            delete $window.sessionStorage.workId;
            delete $window.sessionStorage.role;
            delete $window.sessionStorage.subject;
            delete $window.sessionStorage.markRight;
            callback();
        })
    }

    function getUser(){
        if(!$window.sessionStorage.userId){
            return null;
        }
        return {
            id:$window.sessionStorage.userId,
            name:$window.sessionStorage.name,
            workId:$window.sessionStorage.workId,
            role: $window.sessionStorage.role,
            subject:$window.sessionStorage.subject,
            markRight:$window.sessionStorage.markRight
        };
    }
    function isAuthenticated() { 
        var authData = getUser();
        return !!authData;
    }

    function changePassword(password){
        return $http.patch(HOST+getUser().id+'/password',{password:password});
    }


    ///////////////

    function remove(userId){
        return $http.delete(baseUrl+'/'+userId);
    }

    function save(user){
        if(user.id){
            return $http.put(baseUrl+'/'+user.id,user);
        }
        else{
            return $http.post(baseUrl,user);
        }
    }

    function list(markSubjectId,role){
        var workId = markSubjectId.split('-')[0];
        var subject = markSubjectId.split('-')[1];
        var params = '?workId='+workId+'&subject='+subject;
        if(role){
            params += '&role='+role;
        }
        return $http.get(baseUrl+params);
    }

}